/* 
 * File:   LibraryInterface.cpp
 * Author: sergey
 * 
 * Created on 3 Декабрь 2009 г., 19:32
 */

#include "LibraryInterface.h"

LibraryInterface::LibraryInterface() {
    #ifdef DEBUG
    std::cout << "Error: construct not implemented class LibraryInterface" << std::endl;
    #endif
}

LibraryInterface::~LibraryInterface() {
    #ifdef DEBUG
    std::cout << "Error: destruct not implemented class LibraryInterface" << std::endl;
    #endif
}

void LibraryInterface::readFileOpen(const std::string filename) {
    std::cout << "Opening file: " << filename << " ";
    readBinFile.open(filename.c_str(), std::ios::in | std::ios::binary);
    if (!readBinFile.fail())
         std::cout << "success." << std::endl;
    else 
         std::cout << "NOT SUCCESS." << std::endl;
    
}

void LibraryInterface::readFileClose() {
    readBinFile.close();
}

void LibraryInterface::read4bit(UInt8 &s) {
    if (isEmptyRead4bitBuffer) {
        readInt(read4bitBuffer);
        s = read4bitBuffer >> 4;
        isEmptyRead4bitBuffer = false;
    } else {
        s = read4bitBuffer & 31;
        isEmptyRead4bitBuffer = true;
    }
}

void LibraryInterface::writeFileOpen(const std::string filename) {
    writeBinFile.open(filename.c_str(), std::ios::out | std::ios::binary);
    reset();
}

void LibraryInterface::writeFileClose() {
    _write4bit();
    writeBinFile.close();
}

void LibraryInterface::write4bit(const UInt8 s) {
    write4bitBuffer <<= 4;
    #ifdef DEBUG
    if (s >= 32) std::cout << "Error: LibraryInterface.write4bit("<< s << ");" << std::endl;
    #endif
    write4bitBuffer += s;
    if (isEmptyWrite4bitBuffer) {
        isEmptyWrite4bitBuffer = false;
    } else {
        writeInt(write4bitBuffer);
        write4bitBuffer = 0;
        isEmptyWrite4bitBuffer = true;
    }
}

void LibraryInterface::_write4bit() {    
    if (!isEmptyWrite4bitBuffer) {
        isEmptyWrite4bitBuffer = true;
        writeInt(write4bitBuffer << 4);        
    }
}
